function [psnrsAll, ssimsAll, BestModel, ModelIters] = analyIterModels(X, Y, scale, net, ModelIters, solver_mode, pre_results)
% Input:
%   --X: LR image
%   --Y: HR image

%%
if iscell(ModelIters)
    [ModelFiles, ModelIters] = ModelIters{:};
else
    [ModelFiles, ModelIters] = mycaffe.getModelFiles(net.model_path, net.model_prefix, ModelIters);
end
ModelNum = length(ModelFiles);

%%
[border_size, block_size] = srmodel.get_blocksize(net.name);
% h = waitbar(0, sprintf('Analyze Iterative Models of "%s", Please wait ...', net.name));
psnrsAll = cell(1, ModelNum); ssimsAll = psnrsAll;
mycaffe.init(solver_mode, net.name);
for k = 1 : ModelNum
    % fprintf('%d / %d\n', j, ModelNum);
    % waitbar(k / ModelNum, h);
    caffemodel = fullfile(net.model_path, ModelFiles{k});
    hDeploy = @(x) mycaffe.caffe(x, net.deploy_file, caffemodel, 'test');
    hDeploy = @(X) srmodel.deploy(X, hDeploy, block_size, border_size);
    
    [psnrsAll{k}, ssimsAll{k}] = sranaly.analySRQuality(X, Y, scale, net.name, hDeploy, []);
    
    fprintf('%s: %d / %d, mean(PSNR/SSIM) = %.2f/%.4f\n', net.name, k, ModelNum, mean(psnrsAll{k}), mean(ssimsAll{k}));
end
% close(h)

%%
psnrsAll = [psnrsAll{:}];  ssimsAll = [ssimsAll{:}];
% if nargout < 3, return; end

psnr_bar = mean(psnrsAll);  ssim_bar  = mean(ssimsAll);

[max_psnr, idx1] = max(psnr_bar); [max_ssim, idx2] = max(ssim_bar);
BestModel.PSNR = ModelFiles{idx1};
BestModel.SSIM = ModelFiles{idx2};

%%
if exist('pre_results', 'var') && ~isempty(pre_results)
    if max(mean(pre_results{1})) > max_psnr
        BestModel.PSNR = pre_results{3}.PSNR;
    end
    if max(mean(pre_results{2})) > max_ssim
        BestModel.SSIM = pre_results{3}.SSIM;
    end
    
    psnrsAll = [pre_results{1} psnrsAll];
    ssimsAll = [pre_results{2} ssimsAll];
    
    ModelIters = [pre_results{end} ModelIters];
    [ModelIters, Idx] = sort(ModelIters);
    psnrsAll = psnrsAll(:, Idx);
    ssimsAll = ssimsAll(:, Idx);
end
